/**
 * 最终版AI对话功能
 * 使用绝对定位而不是transform，避免坐标冲突
 */

/**
 * 全局调试函数
 * @param {string} message - 调试信息
 */
function debugLog(message) {
  const debugElement = document.getElementById("debug-log");
  if (debugElement) {
    const timestamp = new Date().toLocaleTimeString();
    debugElement.innerHTML += `[${timestamp}] ${message}\n`;
    debugElement.scrollTop = debugElement.scrollHeight;
  }
  console.log(`[AI-Chat] ${message}`);
}

/**
 * 初始化最终版AI对话功能
 */
function initFinalAiChat() {
  const chatButton = document.getElementById("aiChatButton");
  const chatModal = document.getElementById("aiChatModal");

  if (!chatButton || !chatModal) {
    debugLog("❌ AI聊天元素未找到");
    return;
  }

  debugLog("🚀 最终版AI聊天功能初始化开始");

  // 拖拽状态
  let isDragging = false;
  let dragStartTime = 0;
  let hasMoved = false;

  // 鼠标起始位置
  let startMouseX = 0;
  let startMouseY = 0;

  // 按钮起始位置
  let startButtonX = 0;
  let startButtonY = 0;

  // 按钮大小和边距
  const BUTTON_SIZE = 60;
  const EDGE_MARGIN = 30;
  const TOP_MARGIN = 100;

  /**
   * 设置按钮绝对位置
   * @param {number} x - X坐标
   * @param {number} y - Y坐标
   */
  function setButtonPosition(x, y) {
    // 限制在屏幕范围内
    const maxX = window.innerWidth - BUTTON_SIZE - EDGE_MARGIN;
    const maxY = window.innerHeight - BUTTON_SIZE - EDGE_MARGIN;

    const finalX = Math.max(EDGE_MARGIN, Math.min(maxX, x));
    const finalY = Math.max(TOP_MARGIN, Math.min(maxY, y));

    // 使用绝对定位而不是transform
    chatButton.style.left = finalX + "px";
    chatButton.style.top = finalY + "px";
    chatButton.style.right = "auto";
    chatButton.style.bottom = "auto";

    // 应用缩放效果
    if (isDragging) {
      chatButton.style.transform = "scale(1.05)";
    } else {
      chatButton.style.transform = "scale(1)";
    }

    debugLog(`📍 设置位置: (${x}, ${y}) -> (${finalX}, ${finalY})`);

    return { x: finalX, y: finalY };
  }

  /**
   * 获取按钮当前位置
   * @returns {Object} 当前位置坐标
   */
  function getCurrentPosition() {
    const rect = chatButton.getBoundingClientRect();
    return {
      x: rect.left,
      y: rect.top,
    };
  }

  /**
   * 开始拖拽
   * @param {Event} e - 事件对象
   */
  function handleStart(e) {
    debugLog("🖱️ 开始拖拽");

    dragStartTime = Date.now();
    hasMoved = false;
    isDragging = true;

    // 获取鼠标/触摸位置
    if (e.type.includes("touch")) {
      startMouseX = e.touches[0].clientX;
      startMouseY = e.touches[0].clientY;
    } else {
      startMouseX = e.clientX;
      startMouseY = e.clientY;
    }

    // 获取按钮当前位置
    const currentPos = getCurrentPosition();
    startButtonX = currentPos.x;
    startButtonY = currentPos.y;

    chatButton.classList.add("dragging");
    e.preventDefault();

    debugLog(
      `📌 起始位置: 鼠标(${startMouseX}, ${startMouseY}) 按钮(${startButtonX}, ${startButtonY})`
    );
  }

  /**
   * 拖拽移动
   * @param {Event} e - 事件对象
   */
  function handleMove(e) {
    if (!isDragging) return;

    e.preventDefault();

    // 获取当前鼠标/触摸位置
    let currentMouseX, currentMouseY;
    if (e.type.includes("touch")) {
      currentMouseX = e.touches[0].clientX;
      currentMouseY = e.touches[0].clientY;
    } else {
      currentMouseX = e.clientX;
      currentMouseY = e.clientY;
    }

    // 计算移动距离
    const deltaX = currentMouseX - startMouseX;
    const deltaY = currentMouseY - startMouseY;

    // 计算新位置
    const newX = startButtonX + deltaX;
    const newY = startButtonY + deltaY;

    // 检查是否真的移动了
    const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
    if (distance > 3) {
      hasMoved = true;
    }

    setButtonPosition(newX, newY);

    debugLog(
      `🏃 移动中: delta(${deltaX}, ${deltaY}) 新位置(${newX}, ${newY}) 距离=${distance.toFixed(
        1
      )}`
    );
  }

  /**
   * 结束拖拽
   * @param {Event} e - 事件对象
   */
  function handleEnd(e) {
    if (!isDragging) return;

    const dragDuration = Date.now() - dragStartTime;
    isDragging = false;
    chatButton.classList.remove("dragging");

    debugLog(`🏁 结束拖拽: 持续${dragDuration}ms 移动=${hasMoved}`);

    // 应用最终缩放
    chatButton.style.transform = "scale(1)";

    // 如果没有移动且时间很短，认为是点击
    if (!hasMoved && dragDuration < 300) {
      debugLog("👆 触发点击事件");
      setTimeout(() => {
        openChatModal();
      }, 50);
    } else if (hasMoved) {
      // 拖拽后吸附到边缘
      snapToEdge();
    }
  }

  /**
   * 吸附到边缘
   */
  function snapToEdge() {
    const currentPos = getCurrentPosition();
    const windowWidth = window.innerWidth;
    const centerX = currentPos.x + BUTTON_SIZE / 2;

    let targetX;
    if (centerX < windowWidth / 2) {
      targetX = EDGE_MARGIN; // 吸附到左边
    } else {
      targetX = windowWidth - BUTTON_SIZE - EDGE_MARGIN; // 吸附到右边
    }

    debugLog(`🧲 吸附到边缘: 中心X=${centerX} 目标X=${targetX}`);

    // 平滑移动到目标位置
    chatButton.style.transition = "left 0.3s ease, top 0.3s ease";
    setButtonPosition(targetX, currentPos.y);

    setTimeout(() => {
      chatButton.style.transition = "";
    }, 300);
  }

  /**
   * 打开对话弹窗
   */
  function openChatModal() {
    debugLog("💬 打开对话弹窗");
    chatModal.classList.add("active");

    // 如果没有欢迎消息，显示一个
    const messagesContainer = chatModal.querySelector(".ai-chat-messages");
    if (messagesContainer && messagesContainer.children.length === 0) {
      showWelcomeMessage();
    }
  }

  /**
   * 关闭对话弹窗
   */
  function closeChatModal() {
    debugLog("❌ 关闭对话弹窗");
    chatModal.classList.remove("active");
  }

  /**
   * 显示欢迎消息
   */
  function showWelcomeMessage() {
    const messagesContainer = chatModal.querySelector(".ai-chat-messages");
    const welcomeHTML = `
            <div class="welcome-message">
                <i class="fas fa-robot"></i>
                <h3>您好！我是非遗索思AI助手</h3>
                <p>  
关于“非遗+科学课堂”，我十分乐意为您解疑答惑。欢迎您随时向我提问！</p>
            </div>
        `;
    messagesContainer.innerHTML = welcomeHTML;
  }

  /**
   * 发送消息
   * @param {string} message - 用户消息
   */
  function sendMessage(message) {
    if (!message.trim()) return;

    debugLog(`📤 发送消息: ${message}`);

    const messagesContainer = chatModal.querySelector(".ai-chat-messages");

    // 添加用户消息
    addMessage("user", message);

    // 清空输入框
    const input = chatModal.querySelector(".ai-chat-input");
    if (input) input.value = "";

    // 模拟AI回复
    setTimeout(() => {
      const aiReply = generateAIReply(message);
      addMessage("ai", aiReply);
    }, 1000);
  }

  /**
   * 添加消息到对话
   * @param {string} sender - 发送者 ('user' 或 'ai')
   * @param {string} message - 消息内容
   */
  function addMessage(sender, message) {
    const messagesContainer = chatModal.querySelector(".ai-chat-messages");
    const messageHTML = `
            <div class="chat-message ${sender}">
                <div class="message-avatar ${sender}">
                    <i class="fas ${
                      sender === "user" ? "fa-user" : "fa-robot"
                    }"></i>
                </div>
                <div class="message-content">
                    ${message}
                </div>
            </div>
        `;
    messagesContainer.insertAdjacentHTML("beforeend", messageHTML);
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
  }

  /**
   * 生成AI回复
   * @param {string} userMessage - 用户消息
   * @returns {string} AI回复
   */
  function generateAIReply(userMessage) {
    const message = userMessage.toLowerCase();

    if (message.includes("龙舟") || message.includes("赛龙舟")) {
      return "龙舟竞渡是中华民族传统的水上体育娱乐项目，已流传两千多年，是中国历史上一种具有浓郁的民俗文化色彩的群众性娱乐活动。";
    } else if (message.includes("剪纸")) {
      return "中国剪纸是一种用剪刀或刻刀在纸上剪刻花纹，用于装点生活或配合其他民俗活动的民间艺术。在中国，剪纸具有广泛的群众基础。";
    } else if (message.includes("茶") || message.includes("茶艺")) {
      return "中国茶艺是一种文化。茶艺在中国优秀文化的基础上又广泛吸收和借鉴了其它艺术形式，并扩展到文学、艺术等领域。";
    } else if (message.includes("你好") || message.includes("hello")) {
      return "您好！我是非遗索思AI助手，很高兴为您服务。请问您想了解哪方面的非物质文化遗产知识呢？";
    } else {
      return "感谢您的提问！中华非物质文化遗产博大精深，包含了民间文学、传统音乐、传统舞蹈、传统戏剧、曲艺、传统体育与杂技、传统美术、传统技艺、传统医药和民俗等多个类别。如果您有具体想了解的项目，请随时告诉我！";
    }
  }

  // 绑定拖拽事件
  chatButton.addEventListener("mousedown", handleStart);
  document.addEventListener("mousemove", handleMove);
  document.addEventListener("mouseup", handleEnd);

  // 触摸事件
  chatButton.addEventListener("touchstart", handleStart, { passive: false });
  document.addEventListener("touchmove", handleMove, { passive: false });
  document.addEventListener("touchend", handleEnd);

  // 弹窗关闭事件
  const closeButton = chatModal.querySelector(".ai-chat-close");
  if (closeButton) {
    closeButton.addEventListener("click", closeChatModal);
  }

  // 点击遮罩关闭
  chatModal.addEventListener("click", function (e) {
    if (e.target === chatModal) {
      closeChatModal();
    }
  });

  // 发送消息事件
  const sendButton = chatModal.querySelector(".ai-chat-send");
  const inputField = chatModal.querySelector(".ai-chat-input");

  if (sendButton) {
    sendButton.addEventListener("click", function () {
      const message = inputField ? inputField.value : "";
      sendMessage(message);
    });
  }

  if (inputField) {
    inputField.addEventListener("keypress", function (e) {
      if (e.key === "Enter" && !e.shiftKey) {
        e.preventDefault();
        const message = inputField.value;
        sendMessage(message);
      }
    });
  }

  // 初始化按钮位置到右下角
  function initButtonPosition() {
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;

    const initX = windowWidth - BUTTON_SIZE - EDGE_MARGIN;
    const initY = windowHeight - BUTTON_SIZE - EDGE_MARGIN;

    setButtonPosition(initX, initY);

    debugLog(
      `🎯 初始化位置: (${initX}, ${initY}) 窗口: ${windowWidth}x${windowHeight}`
    );
  }

  // 设置初始位置
  initButtonPosition();

  // 窗口大小改变时重新计算位置
  window.addEventListener("resize", function () {
    debugLog("📱 窗口大小改变，重新计算位置");
    const currentPos = getCurrentPosition();
    setButtonPosition(currentPos.x, currentPos.y);
  });

  debugLog("✅ 最终版AI聊天功能初始化完成");
}

// 页面加载完成后初始化
document.addEventListener("DOMContentLoaded", function () {
  // 确保不与主页面动画冲突，延迟更久
  setTimeout(() => {
    initFinalAiChat();
  }, 500);
});
